#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRegularExpression>
#include <QDateTime>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QValueAxis>
#include <csignal>  // 添加这个头文件
#include <QNetworkInterface>  // 网络接口相关
#include <QHostAddress>       // IP地址处理
#include <QDebug>

int MainWindow::getModuleCode(const QString& alarmName)
{
    static QMap<QString, int> moduleMap = {
        {"Vacuum", 1},
        {"Current", 2},
        {"CCD1", 4}, 
        {"CCD2", 4}, // ...所有温度传感器
        {"Other", 8}
    };
    return moduleMap.value(alarmName, 8);
}

void MainWindow::sendRecoveryToServer(const QString& alarmName)
{
    QJsonObject recoveryData;
    recoveryData["status"] = 1; // 正常状态
    recoveryData["module"] = getModuleCode(alarmName);
    recoveryData["reason"] = QString("%1 恢复正常范围").arg(alarmName);
    recoveryData["timestamp"] = QDateTime::currentDateTime().toString(Qt::ISODate);

    // ...发送POST请求（同sendAlarmToServer）
}

void MainWindow::sendCameraCommand(const QString &cmd) {
    if (!cameraSocket || !cameraSocket->isValid()) {
        LOG_CAMERA("Camera UDP Socket not ready");
        return;
    }

    QByteArray data = cmd.toUtf8();
    cameraSocket->writeDatagram(data, QHostAddress(cameraIp), cameraPort);
    LOG_CAMERA("sent command to camera: " + cmd);
}

//新增配置界面的手动输入通信方法
void MainWindow::onSendCameraCommand()
{
    QString cmd = ui->cameraCommandEdit->text();
    LOG_CAMERA("向相机发送指令: " + cmd);
    if(!cmd.isEmpty()){
        sendCameraCommand(cmd);
    }
}


void MainWindow::resetImageCounter()
{
    m_localImageCounter = 0;
    ui->lineEditImgNum->setText("0");
}

QDateTime MainWindow::parseCameraTimestamp(const QString& timestampStr)
{
    // 格式: YYMMDDhhmmssSSS (年(2位)月日时分秒毫秒)
    if (timestampStr.length() != 15) {
        LOG_CAMERA("Invalid timestamp format: " + timestampStr);
        return QDateTime();
    }

    int year = 2000 + timestampStr.mid(0, 2).toInt(); // 假设21世纪
    int month = timestampStr.mid(2, 2).toInt();
    int day = timestampStr.mid(4, 2).toInt();
    int hour = timestampStr.mid(6, 2).toInt();
    int minute = timestampStr.mid(8, 2).toInt();
    int second = timestampStr.mid(10, 2).toInt();
    int msec = timestampStr.mid(12, 3).toInt();

    return QDateTime(QDate(year, month, day),
                     QTime(hour, minute, second, msec));
}


// 重置计数器
void MainWindow::resetFrameCounter() {
    frameDoneCount = 0;
    currentTag.clear();
}

/*
    往哪个客户端发送响应？？？
*/
void MainWindow::sendResponse(const QString &response, QTcpSocket *client)
{
    if (!client) {
        qDebug() << "[Error] Client socket is null";
        return;
    }

    qDebug() << "Sending response before:" << response;

    if (client->state() != QAbstractSocket::ConnectedState) {
        qDebug() << "[Warning] Client not connected, skipping response";
        return;
    }

    qDebug() << "Sending response after:" << response;
    client->write(response.toUtf8());

    // 注意：这里不再主动断开连接，由调用方控制
}

void MainWindow::handleClientError(QTcpSocket *client)
{
    if (!client) return;

    QString clientKey = QString("%1:%2").arg(client->peerAddress().toString())
                            .arg(client->peerPort());

    // 记录错误信息
    LOG_CAMERA(QString("Client error occurred: %1 (state: %2)")
                   .arg(client->errorString())
                   .arg(client->state()));

    // 从客户端列表中移除
    clientSockets.remove(clientKey);

    // 安全关闭和删除客户端
    if (client->state() != QAbstractSocket::UnconnectedState) {
        client->disconnectFromHost();
        if (client->state() != QAbstractSocket::UnconnectedState) {
            client->abort();
        }
    }
    client->deleteLater();
}

